<script lang="ts" setup>
import api from "@/api";
import { onMounted, reactive, ref } from "vue";
import type { PageDTO, TopologyDTO } from "@/types";
import { TopologyPageQry } from "@/types";
import TopologySave from "./TopologySave.vue";
import { useDelete } from "@/hooks";
import { useRouter } from "vue-router";

const router = useRouter();

const saveRef = ref<InstanceType<typeof TopologySave>>();

interface State {
  loading: boolean;
  qry: TopologyPageQry;
  result: PageDTO<TopologyDTO>;
}

const state = reactive<State>({
  loading: false,
  qry: new TopologyPageQry(),
  result: {
    current: 1,
    data: [],
    size: 10,
    totalPage: 1,
    totalSize: 0
  }
});

const loadData = () => {
  state.loading = true;
  api.topology
    .getPage(state.qry)
    .then((res) => {
      state.result = res.data;
    })
    .finally(() => {
      state.loading = false;
    });
};

const handleDelete = (id: string) => {
  useDelete(() => api.topology.deleteById(id)).then(loadData);
};

const handleSave = (id?: string) => {
  saveRef.value?.openDialog(id);
};

const handleEditTopology = (row: TopologyDTO) => {
  const { href } = router.resolve({
    name: "topologyEditor",
    query: {
      id: row.id
    }
  });
  window.open(href, "_blank");
};

const handlePreviewTopology = (row: TopologyDTO) => {
  router.push({
    name: "topologyPreview",
    query: {
      id: row.id
    }
  });
};

const handlePageSizeChange = () => {
  state.qry.current = 1;
  loadData();
};

onMounted(() => {
  loadData();
});
</script>
<template>
  <div p-2>
    <el-button type="primary" @click="handleSave()">新建</el-button>
  </div>
  <el-table flex-1 :data="state.result.data"
            border
            stripe
            resizablel
            style="width: 100%" v-loading="state.loading">
    <el-table-column type="index" width="50" label="#"></el-table-column>
    <el-table-column prop="name" label="名称"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleSave(scope.row.id)"> 编辑 </el-button>
        <el-button size="small" @click="handleEditTopology(scope.row)"> 拓扑 </el-button>
        <el-button size="small" @click="handlePreviewTopology(scope.row)"> 预览 </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    size="small"
    background
    layout="total, prev, pager, next, sizes, jumper"
    :total="state.result.totalSize"
    v-model:page-size="state.qry.size"
    v-model:current-page="state.qry.current"
    @update:current-page="loadData"
    @update:page-size="handlePageSizeChange"
    p-5
  />
  <topology-save ref="saveRef" @success="loadData" />
</template>
